package com.mrlv.rabbitmq;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author Mrlv
 * @version 1.0
 * @description: 题目 距离说明集合线程不安全
 * 1.故障现象
 * java.util.ConcurrentModificationException
 *
 * 2.导致原因
 *
 * 3.解决方案
 *  3.1 Vector
 *  3.2 Collections.synchronizedList(new ArrayList<>());
 *  3.3 CopyOnWriteArrayList
 *
 *
 * @date 2021年11月18日 11:21
 */
public class NotSafeDemo {

    public static void main(String[] args) {

        mapNotSafe();
    }

    public static void mapNotSafe() {

        Map<String, String> map = new ConcurrentHashMap();//Collections.synchronizedMap( new HashMap<>())

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
    }

    public static void setNotSafe() {

        Set<String> set = new CopyOnWriteArraySet();//Collections.synchronizedSet(new HashSet<>());//new HashSet

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            }, String.valueOf(i)).start();
        }
    }

    public static void listNotSafe() {

        List<String> list = new CopyOnWriteArrayList<>();//Collections.synchronizedList(new ArrayList<>()); //new Vector<>();  //new ArrayList

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }, String.valueOf(i)).start();
        }
    }
}
